package main

import (
	"encoding/json"
	"fmt"
	"gitee.com/ichub/goconfig/common/ichubconfig"
	"gitee.com/ichub/gofactroy/common/ichubbase"
	"gitee.com/ichub/gofactroy/factroy/dbfactroy"
	"gitee.com/ichub/gofactroy/nats/msg2nets"
	"github.com/jinzhu/gorm"
	"github.com/nats-io/nats.go"
	"log"
	"time"
)

var Nc *nats.Conn

// 邀请码注册消息主题
const SubjReg = "UserRegMsg2Cms"
const Nats_URL = "nats://192.168.4.119:4222"
const SubjOrder = "OrderFinishMsg2Cms"

var cfg = ichubconfig.NewConfig()

// AdCode
type OrderFinishMsg2Cms struct {
	//广告码
	Code string
	//用户id
	UserId int64
	//订单标识
	OrderId, OrderLineId string

	//订单完成时间 s
	FinishedTime int64
}

// 前端链接注册，header增加邀请码 InviteCode
type UserRegMsg2Cms struct {
	//邀请注册
	//邀请码
	InviteCode string
	//用户id
	UserId int64
	//注册时间 s
	RegTime int64
}

func (entity *UserRegMsg2Cms) String() string {
	s, err := json.Marshal(entity)
	if err != nil {
		fmt.Println(err.Error())
		return "{}"
	}
	return string(s)

}
func (entity *UserRegMsg2Cms) Unmarshal(body string) error {
	return json.Unmarshal([]byte(body), entity)

}
func (entity *UserRegMsg2Cms) ToString() string {
	s, err := json.MarshalIndent(entity, "", " ")
	if err != nil {
		fmt.Println(err.Error())
		return "{}"
	}
	return string(s)

}
func UserRegReplyHandler(m *nats.Msg) {
	fmt.Printf("Received a message: %s\n", string(m.Data))
	resmsg := UserRegMsg2Cms{}
	err := resmsg.Unmarshal(string(m.Data))
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println("接收了邀请码注册消息：" + resmsg.ToString())
}
func roachDBUrlConnPG() string {
	var dto = cfg.ReadIchubMysql()
	return dto.MakeCockroachUrl() //"postgresql://root@192.168.4.119:26257/" + ichubbase.DBNAME + "?sslmode=disable"

}
func main() {
	//url := "nats://192.168.4.119:4222"
	var dto = cfg.ReadIchubMysql()
	tabletool := &dbfactroy.DbFactroy{
		Dbtype_mysql: false,
		Db:           dto.Dbname,
		Table:        "employee",
		Author:       "leijianming",
		ModuleName:   ichubbase.MODULE_MAP[ichubbase.APP], //MODULE_NAME,
	}

	dBUrl := roachDBUrlConnPG()

	var dbinst *gorm.DB = tabletool.InitDb(dBUrl) //  dbcontent.InitDB_pg(pgDBUrlConn())
	defer dbinst.Close()
	nc, err := nats.Connect(Nats_URL)
	Nc = nc

	if err != nil {
		log.Fatal(err)
	}
	defer Nc.Close()

	// 订阅
	Nc.Subscribe(SubjOrder, func(m *nats.Msg) {
		go UserRegReplyHandler(m)
	})

	// 发布
	Nc.Publish(SubjReg, []byte("Hello World!"))
	regmsg := UserRegMsg2Cms{}
	regmsg.InviteCode = "A233112222"
	regmsg.UserId = 1
	regmsg.RegTime = time.Now().Unix()

	Nc.Publish(SubjReg, []byte(regmsg.String()))
	//Nc.Request(SubjReg, []byte("Hello help"), 50*time.Millisecond)
	natsMessage := msg2nats.NatsMessage{}
	natsMessage.Header.Topic = SubjReg

	natsMsg := msg2nats.NatsManager{
		Nc: Nc,
	}
	regmsg.InviteCode = "A123456"
	err = natsMsg.Subscribe(SubjReg)
	if err != nil {
		fmt.Println(err)
		return
	}
	err = natsMsg.PublishData(natsMessage, []byte(regmsg.String()))
	if err != nil {
		fmt.Println(err)
		return
	}
	time.Sleep(1e7)

}
